package zhoug.common.utils;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;

import zhoug.common.interfaces.Execution;
import zhoug.logging.Logger;

import java.util.Objects;

/**
 * @Author: zhoug
 * @Date: 2023/9/7
 * @Description:
 */
public class ViewUtils {

    private static final String TAG = ">>>ViewUtils";

    /**
     * 清除view中获取焦点的view的焦点
     *
     * @param viewGroup
     */
    public static void clearChildFocus(ViewGroup viewGroup) {
        if (viewGroup == null) return;
        View focus = viewGroup.findFocus();
        Logger.d(TAG, "focusView:" + focus);
        if (focus != null) {
            focus.clearFocus();
        }
    }

    /**
     * 清除当前页面上的焦点
     *
     * @param view
     */
    public static void clearPageFocus(View view) {
        if (view != null) {
            View currentFocus = getCurrentFocusView(view);
            if (currentFocus != null) {
                currentFocus.clearFocus();
            }
        }
    }

    /**
     * 给定一个View查找当前Window上获取到焦点的View
     *
     * @param view
     * @return
     */
    public static View getCurrentFocusView(View view) {
        if (view != null) {
            if (view.hasFocus()) {
                return view.findFocus();
            } else if (view.getContext() instanceof Activity) {
                return ((Activity) view.getContext()).getCurrentFocus();
            } else {
                View rootView = view.getRootView();
                if (rootView != null) {
                    return rootView.findFocus();
                }
            }
        }
        return null;
    }


    /**
     * 查找指定的View 不包含继承的子类
     * @param viewGroup 哪个容器中查找
     * @param clz 指定的View
     * @param fun
     * @param <T>
     */
    public static <T> void findView(ViewGroup viewGroup, Class<T> clz, Execution<T> fun) {
        findView(viewGroup,clz,false,fun);
    }

    /**
     * 查找指定的View
     * @param viewGroup 哪个容器中查找
     * @param clz 指定的View
     * @param extendsView 是否包含继承{@param clz}的子类
     * @param fun
     * @param <T>
     * @noinspection unchecked
     */
    public static <T> void findView(ViewGroup viewGroup, Class<T> clz,boolean extendsView, Execution<T> fun) {
        if (viewGroup == null || clz == null) return;
        Objects.requireNonNull(fun);
        int childCount = viewGroup.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = viewGroup.getChildAt(i);
            if(extendsView){
                if(clz.isAssignableFrom(child.getClass())){
                    fun.execute((T) child);
                }
            }else{
                if (clz == child.getClass()) {
                    fun.execute((T) child);
                }
            }

            if (child instanceof ViewGroup childViewGroup) {
                findView(childViewGroup, clz,extendsView, fun);
            }
        }
    }
}
